import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../../shared/widgets/fancy_header.dart';
import '../../../shared/widgets/aurora_background.dart';
import '../../../shared/widgets/animated_appear.dart';
import '../../../shared/utils/responsive_utils.dart';

class ExplainPage extends StatefulWidget {
  const ExplainPage({super.key});

  @override
  State<ExplainPage> createState() => _ExplainPageState();
}

class _ExplainPageState extends State<ExplainPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool _isLiked = false;
  bool _isBookmarked = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            if (context.canPop()) {
              context.pop();
            } else {
              context.go('/dashboard');
            }
          },
        ),
        title: const Text('AI讲解'),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              setState(() {
                _isLiked = !_isLiked;
              });
            },
            icon: Icon(
              _isLiked ? Icons.favorite : Icons.favorite_border,
              color: _isLiked ? Colors.red : null,
            ),
          ),
          IconButton(
            onPressed: () {
              setState(() {
                _isBookmarked = !_isBookmarked;
              });
            },
            icon: Icon(
              _isBookmarked ? Icons.bookmark : Icons.bookmark_border,
              color: _isBookmarked ? Colors.blue : null,
            ),
          ),
        ],
      ),
      body: Stack(
        children: <Widget>[
          const AuroraBackground(),
          Column(
            children: <Widget>[
              const FancyHeader(
                title: 'AI讲解',
                subtitle: '跟着步骤慢慢来，不着急～需要时点右上角收藏哦',
                icon: Icons.menu_book,
                height: 120,
              ),
              _buildQuestionCard(),
              _buildTabBar(),
              Expanded(child: _buildTabBarView()),
              _buildBottomActions(),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionCard() {
    final scaleFactor = ResponsiveUtils.getScaleFactor(context);
    return Container(
      margin: EdgeInsets.all(ResponsiveUtils.getResponsiveSpacing(context, 16)),
      padding: EdgeInsets.all(
        ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(
          ResponsiveUtils.getResponsiveRadius(context, 12),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: ResponsiveUtils.getResponsiveSpacing(context, 8),
                  vertical: ResponsiveUtils.getResponsiveSpacing(context, 4),
                ),
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.primaryContainer,
                  borderRadius: BorderRadius.circular(
                    ResponsiveUtils.getResponsiveRadius(context, 12),
                  ),
                ),
                child: Text(
                  '数学',
                  style: Theme.of(context).textTheme.labelSmall?.copyWith(
                    color: Theme.of(context).colorScheme.primary,
                    fontWeight: FontWeight.w600,
                    fontSize: ResponsiveUtils.getResponsiveFontSize(
                      context,
                      12,
                    ),
                  ),
                ),
              ),
              SizedBox(width: ResponsiveUtils.getResponsiveSpacing(context, 8)),
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: ResponsiveUtils.getResponsiveSpacing(context, 8),
                  vertical: ResponsiveUtils.getResponsiveSpacing(context, 4),
                ),
                decoration: BoxDecoration(
                  color: Colors.orange.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(
                    ResponsiveUtils.getResponsiveRadius(context, 12),
                  ),
                ),
                child: Text(
                  '中等',
                  style: Theme.of(context).textTheme.labelSmall?.copyWith(
                    color: Colors.orange,
                    fontWeight: FontWeight.w600,
                    fontSize: ResponsiveUtils.getResponsiveFontSize(
                      context,
                      12,
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 12)),
          Text(
            '解方程：2x + 3 = 7',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
              fontSize: ResponsiveUtils.getResponsiveFontSize(context, 18),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(
        horizontal: ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      decoration: BoxDecoration(
        color: Theme.of(
          context,
        ).colorScheme.surfaceContainerHighest.withOpacity(0.7),
        borderRadius: BorderRadius.circular(
          ResponsiveUtils.getResponsiveRadius(context, 24),
        ),
        border: Border.all(
          color: Theme.of(context).colorScheme.outline.withOpacity(0.08),
        ),
      ),
      child: TabBar(
        controller: _tabController,
        labelColor: Theme.of(context).colorScheme.primary,
        unselectedLabelColor: Theme.of(
          context,
        ).colorScheme.onSurface.withOpacity(0.6),
        labelStyle: const TextStyle(fontWeight: FontWeight.w700),
        unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600),
        indicatorSize: TabBarIndicatorSize.tab,
        indicatorPadding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 4),
        ),
        overlayColor: MaterialStateProperty.resolveWith(
          (states) => Colors.transparent,
        ),
        indicator: BoxDecoration(
          gradient: LinearGradient(
            colors: <Color>[
              Theme.of(context).colorScheme.primary.withOpacity(0.20),
              Theme.of(context).colorScheme.primary.withOpacity(0.35),
            ],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(
            ResponsiveUtils.getResponsiveRadius(context, 20),
          ),
          border: Border.all(
            color: Theme.of(context).colorScheme.primary.withOpacity(0.35),
            width: 1,
          ),
          boxShadow: <BoxShadow>[
            BoxShadow(
              color: Theme.of(context).colorScheme.primary.withOpacity(0.18),
              blurRadius: ResponsiveUtils.getResponsiveSpacing(context, 8),
              offset: Offset(
                0,
                ResponsiveUtils.getResponsiveSpacing(context, 3),
              ),
            ),
          ],
        ),
        tabs: const <Widget>[
          Tab(text: '思路'),
          Tab(text: '解答'),
          Tab(text: '易错点'),
        ],
      ),
    );
  }

  Widget _buildTabBarView() {
    return TabBarView(
      controller: _tabController,
      children: <Widget>[
        _buildThinkingTab(),
        _buildSolutionTab(),
        _buildErrorPointsTab(),
      ],
    );
  }

  Widget _buildThinkingTab() {
    return ListView(
      padding: EdgeInsets.all(
        ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      children: <Widget>[
        _buildThinkingCard(
          '1. 理解题目',
          '这是一个一元一次方程，需要求解未知数x的值。',
          Icons.lightbulb_outline,
        ),
        _buildThinkingCard(
          '2. 确定解法',
          '使用移项法，将常数项移到等号右边，系数项移到等号左边。',
          Icons.psychology_outlined,
        ),
        _buildThinkingCard(
          '3. 执行计算',
          '按照移项规则，逐步化简方程。',
          Icons.calculate_outlined,
        ),
      ],
    );
  }

  Widget _buildSolutionTab() {
    return ListView(
      padding: EdgeInsets.all(
        ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      children: <Widget>[
        _buildStepCard('步骤1：移项', '2x = 7 - 3', '将常数3移到等号右边'),
        _buildStepCard('步骤2：化简', '2x = 4', '计算7-3=4'),
        _buildStepCard('步骤3：求解', 'x = 2', '两边同时除以2'),
        SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
        Container(
          padding: EdgeInsets.all(
            ResponsiveUtils.getResponsiveSpacing(context, 16),
          ),
          decoration: BoxDecoration(
            color: Colors.green.withOpacity(0.1),
            borderRadius: BorderRadius.circular(
              ResponsiveUtils.getResponsiveRadius(context, 12),
            ),
            border: Border.all(color: Colors.green.withOpacity(0.3)),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                '答案：x = 2',
                style: TextStyle(
                  fontSize: ResponsiveUtils.getResponsiveFontSize(context, 18),
                  fontWeight: FontWeight.bold,
                  color: Colors.green,
                ),
              ),
              SizedBox(
                height: ResponsiveUtils.getResponsiveSpacing(context, 8),
              ),
              Text(
                '验证：将x=2代入原方程，2×2+3=7，等式成立。',
                style: TextStyle(color: Colors.green),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildErrorPointsTab() {
    return ListView(
      padding: EdgeInsets.all(
        ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      children: <Widget>[
        _buildErrorCard(
          '常见错误1',
          '忘记移项时改变符号',
          '移项时要注意正负号的变化',
          Icons.error_outline,
          Colors.red,
        ),
        _buildErrorCard(
          '常见错误2',
          '计算错误',
          '在化简过程中出现计算失误',
          Icons.calculate_outlined,
          Colors.orange,
        ),
        _buildErrorCard(
          '常见错误3',
          '忘记验证',
          '解出答案后忘记代入验证',
          Icons.verified_outlined,
          Colors.blue,
        ),
      ],
    );
  }

  Widget _buildThinkingCard(String title, String content, IconData icon) {
    return AnimatedAppear(
      delayMs: 40,
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: <Widget>[
            Icon(icon, color: Theme.of(context).colorScheme.primary),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    title,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    content,
                    style: TextStyle(
                      color: Theme.of(
                        context,
                      ).colorScheme.onSurface.withOpacity(0.7),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStepCard(String title, String equation, String explanation) {
    return AnimatedAppear(
      delayMs: 60,
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                equation,
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Theme.of(context).colorScheme.primary,
                ),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              explanation,
              style: TextStyle(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorCard(
    String title,
    String error,
    String explanation,
    IconData icon,
    Color color,
  ) {
    return AnimatedAppear(
      delayMs: 80,
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: color.withOpacity(0.3)),
        ),
        child: Row(
          children: <Widget>[
            Icon(icon, color: color),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    title,
                    style: TextStyle(fontWeight: FontWeight.bold, color: color),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    error,
                    style: const TextStyle(fontWeight: FontWeight.w500),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    explanation,
                    style: TextStyle(
                      color: Theme.of(
                        context,
                      ).colorScheme.onSurface.withOpacity(0.7),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomActions() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        border: Border(
          top: BorderSide(
            color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
          ),
        ),
      ),
      child: Row(
        children: <Widget>[
          Expanded(
            child: OutlinedButton.icon(
              onPressed: () {},
              icon: const Icon(Icons.add),
              label: const Text('加入错题本'),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: FilledButton.icon(
              onPressed: () {},
              icon: const Icon(Icons.play_arrow),
              label: const Text('语音讲解'),
            ),
          ),
        ],
      ),
    );
  }
}
